package com.example.blogspring.controller;

import com.example.blogspring.common.HttpResult;
import com.example.blogspring.constant.Constants;
import com.example.blogspring.model.BlogInfo;
import com.example.blogspring.model.UserInfo;
import com.example.blogspring.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/5/20 22:34
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
   private BlogService blogService;
    @RequestMapping("/getall")
    public List<BlogInfo> getBlogList(){
        return blogService.getBlogList();
    }

    @RequestMapping("/getblog")
    public BlogInfo getBlogById(Integer id, HttpServletRequest request){
        BlogInfo blog = blogService.getBlogById(id);
        UserInfo user =(UserInfo) request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if (blog != null && user != null && Objects.equals(blog.getUserId(), user.getId())){
            blog.setLoginUser(1);
        }
        return blog;
    }

    @RequestMapping("/delete")
    public Boolean delete(Integer id){
        Integer result = blogService.delete(id);
        return result == 1;
    }

    @RequestMapping("/update")
    public Boolean update(BlogInfo blogInfo){
        Integer result = blogService.update(blogInfo);
        return result==1;
    }

    @RequestMapping("/add")
    public Boolean add(BlogInfo blogInfo,HttpServletRequest request){
        UserInfo user = (UserInfo) request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if (user == null || user.getId()<0){
            return false;
        }
        blogInfo.setUserId(user.getId());
        Integer result = blogService.add(blogInfo);
        return result==1;
    }

    @RequestMapping("/getallbypage")
    public HttpResult getAllByPage(Integer pindex,Integer psize){
//        参数矫正
        if (pindex ==null || pindex<=1){
            pindex=1;
        }
        if (psize==null || psize <=1){
            psize=1;
        }
        int offset = (pindex-1)*psize;

        List<BlogInfo> list = blogService.getListByPage(psize,offset);

        int total = blogService.getCount();
        double pcountdb = total/(psize*1.0);
        int pconut = (int)Math.ceil(pcountdb);

        HashMap<String,Object> result = new HashMap<>();
        result.put("list",list);
        result.put("pcount",pconut);
        return HttpResult.success(result);
    }
}
